package com.msy.filter;

import com.msy.generated.Greeter;
import org.web3j.abi.EventEncoder;
import org.web3j.abi.EventValues;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.datatypes.Event;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.EthLog;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.util.List;

/**
 * @ClassName TopicFilter
 * @Description TODO
 * @Author 13683
 * @Date 2019/8/14 17:39
 * @Version 1.0
 **/
public class TopicFilter {

    public static void main(String[] args) throws Exception{


        Web3j web3j = Web3j.build(new HttpService());


        // 加载以太坊钱包文件
        Credentials credentials = WalletUtils.loadCredentials("", "D:/Geth/data0/keystore/UTC--2019-08-13T01-23-18.467473100Z--0b1db9ef3f54504a93d48ef966712f30f64105c3");


        ContractGasProvider contractGasProvider = new DefaultGasProvider();

        Greeter contract = Greeter.load("0xC63a5337469f0451EB4aEBf1Fc78456C0dAE42e9",web3j,credentials,contractGasProvider);

//        Greeter contract = Greeter.deploy(web3j,credentials,contractGasProvider,"TEST").send();

        //创建TopicFilter
        EthFilter ethFilter = new EthFilter(DefaultBlockParameterName.EARLIEST,
                DefaultBlockParameterName.LATEST,
                contract.getContractAddress());

        ethFilter.addSingleTopic(EventEncoder.encode(Greeter.MODIFIED_EVENT));

        web3j.ethLogFlowable(ethFilter).subscribe(log -> {
            System.out.println(log);
            System.out.println(FunctionReturnDecoder.decode(log.getData(),Greeter.MODIFIED_EVENT.getNonIndexedParameters()));
        });

//        web3j.transactionFlowable().subscribe(log -> {
//            System.out.println(log.getHash());
//        });

        contract.newGreeting("new_greeting").sendAsync();
    }
}
